<?php
// TODO: needs to have live search for finding pages
// TODO: needs to just have dropdown menu with \t|&nbsp; like word press? for showing pages or use
// the auto complete feature in scriptaculous
    class PagesController extends Application {
        
        function setup()
        {
            $this->actions = array('index','templates','delete','edit_meta',
                                   'show_editable_regions','search_pages',
                                   'edit_content_area','permissions','list_of_pages');
            $this->use_layout('admin_layout.php');
            $this->before_filter('is_logged_in');
            $this->before_filter('has_access');
            use_model('pages','page_content');
        }
        
        function has_access()
        {
            if (!has_access_to('Pages::Access Pages')) {
                flash('error','Sorry but you do not have access to the Pages tool');
                $this->redirect_to(array('controller'=>'admin/dashboard' ));            
            }
        }
        
        // list pages
		function index() 
		{
		    $pages = new Pages();
		    $this->assign_ref('pages',$pages);			    		    
		    
		    if ( isset($_POST['action']) && $_POST['action'] == 'find_by_title' )
		    {
		        // find id by title
		        $title = $_POST['title'];
		        $page = $pages->find( array(
		                                    'search'=>'first',
		                                    'conditions'=>array('title=?',$title) ,
		                                    'fields'=>'id'
		                                    ) );
		        if ( empty($page) )
		        {
		            flash('error','Page not found');
		            $this->redirect_to('index');
		            return;
		        }
		        $id = $page['id'];
		    }
		    
		    if ( isset($_POST['action']) && $_POST['action'] == 'add_page' )
		    {
		        // add new page
		        if ( has_access_to('Pages::Add Pages') && $pages->update_fields($_POST['pages']) )
		        {
		            flash('notice','Page Saved');
		            $goto = rawurlencode('pages[id]').'='.$pages->get('id');
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'index?'.$goto));
		        } else {
		            flash('error','Error saving page');
		        }
		    }
		    
		    if ( isset($_POST['action']) 
		        && $_POST['action'] == 'edit_page' 
		        && has_access_to('Pages::Edit Pages'))
		    {
		        $id = (int) $_POST['pages']['id'];
		        if ( $pages->load($id) && $pages->update_fields($_POST['pages']) )
		        {
		            flash('notice','Page Saved');
		            $goto = rawurlencode('pages[id]').'='.$pages->get('id');
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'index?'.$goto));
		        } else {
		            flash('error','Error saving page');
		        }
		    }
		    $id = isset($id) ? $id : (int) @$_REQUEST['pages']['id'];
		    if ( isset($id) )
		    {
		        if ( $pages->load($id) )
		        {
		            $this->assign('page',$pages->fields);
		        }
		        
		        // load all users and pages permission crap
		        use_model('users');
		        $users = new Users();
		        $this->assign('all_users', $users->get_users_as_list());		        
		        $page_users = $pages->get_page_users($pages->get('id'));
		        $this->assign('page_users', $page_users);	
		        
		        // check if admin is accessing page and bypass any page permissions
		        // if its just a normal user check the page permissions
		        if ( !has_access_to('Admin::Access Admin') 
		             && $has_permissions = $pages->get('has_permissions') )
		        {
		            if ( !in_array($_SESSION['user_id'], array_keys($page_users)) )
                    {
                        flash('error','You do not have permission to edit '.$pages->get('title'));
                        $pages->unload(); // clear out any page values
                        $this->assign('page',array());
                    }
		        }		                        		        		        
		    }
		    
		    // list of pages
    		$all_pages = $pages->get_pages_as_list();
    		
    		// don't include self in all pages list
    		if ($pages->is_loaded()) 
    		{
    		    unset($all_pages[$pages->get('id')]);
		    }
		    $this->assign('all_pages',$all_pages);
		    
		    $this->assign('pages_as_options',$pages->pages_to_list_options());

		    // list of templates
		    $this->assign('templates',$pages->get_templates());
		    
		    // notification of current home page
		    $current_index_page = $pages->get_index_page();
		    if ( !empty($current_index_page) && $current_index_page != $pages->get('index_name'))
		    {
		        $current_index_page_text = '<b>NOTE:</b> You currently have a page selected as your index page. 
		                               <br />Selecting this option will replace that page with this one as your home page';
		    } else {
		        $current_index_page_text = '';
		    }
		    if(empty($current_index_page)) $this->assign('has_no_index',true);
		    $this->assign('current_index_page_text',$current_index_page_text);
		}		
		
		// should render the page with the regions highlighted
		function show_editable_regions()
		{
		    // get page by id
		    if ( !empty($_GET['id']) )
		    {
		        $pages = new Pages();
		        $id    = (int) $_GET['id'];
		        if ( $pages->load($id) )
		        {
		            $this->assign('page',$pages->fields);
		            $this->assign('admin_edit',true);
		            
		            // render page
	                if ( $pages->get('disable_default_layout') )
		            {
		                $this->use_layout(false);
		            } else {
		                $this->use_layout('application.php');
		            }

		            $this->render(array('template'=>'templates/'.$pages->get('template_file')));
		        } else {
		            $this->render(array('inline'=>'page failed to load.'));
		        }
		    }
		}
		
		
		// editing of a singular content area
		function edit_content_area()
		{
		    $this->use_layout(false);
		    if ( isset($_GET['action']) && $_GET['action'] == 'edit_region' )
		    {		        
		        $page_content = new Page_Content();
		        $id = $page_content->find_by_section($_GET['section'],$_GET['page_id']);
		        if ( $page_content->load($id) )
		        {
		            $this->assign('content',$page_content->fields);
		        }
		    }
		    
		    if ( isset($_POST['action']) 
		          && $_POST['action'] == 'edit_content' 
		          && has_access_to('Pages::Edit Pages') )
		    {
		        if ( isset($_POST['cancel']) )
		        {		            
		            $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'show_editable_regions?id='.$_POST['page_id']));
		        }
		        
		        $id = (int) $_POST['id'];
		        $page_content = new Page_Content();
		        $page_content->load($id);
		        $page_content->update_fields($_POST);		      
		        
		        $this->redirect_to(array('controller'=>'admin/pages' ,'action'=>'show_editable_regions?id='.$_POST['page_id']));
		    }
		    
		}
		
		function edit_meta()
		{
		    if ( isset($_POST['action']) 
		         && $_POST['action'] == 'edit_meta'  
		         && has_access_to('Pages::Edit Pages') )
		    {
		        $pages = new Pages();
		        $id = (int) $_POST['pages']['id'];
		        if ( $pages->load($id) && $pages->update_fields($_POST['pages']) )
		        {
		            $this->render( array('inline'=>'Meta Information Saved') );
		            return;
		        }
		    }
		    $this->redirect_to('index');
		}
		
		// delete a page
		function delete()
		{
		    if ( isset($_POST['action']) 
		        && $_POST['action'] == 'delete' 
		        && !empty($_POST['id']) 
		        && has_access_to('Pages::Delete Pages') )
		    {
		        $pages = new Pages();
		        $id = (int) $_POST['id'];
		        if ( $pages->load($id) && $pages->delete() )
		        {
		            flash('notice','Page Deleted');
		        } else {
		            flash('error','Page has been deleted. If it had children pages, they have been moved to the deleted parent parents page. Sorry if this is confusing.');
		        }
		    }
		    $this->redirect_to('index');
		}
		
		// used in the autocomplete search box
		function search_pages()
		{
		    $pages = new Pages();
		    $found_pages = $pages->find( array(
		                                'conditions'=>array('lower(title) like ?', '%'.strtolower($_POST['title']).'%'),
		                                'order' =>'title asc',
		                                'limit'=>8,
		                                'fields'=>'title'
		                                ) );
		    
		    $this->assign('found_pages',$found_pages);
		    $this->render(array('partial'=>'_found_pages.php'));
		}

        // edit templates found in views folder?
		// views/pages/templates ?
		function templates()
		{
		    $pages = new Pages();
		    $this->assign('templates',$pages->get_templates(true));
		    
		    // write template
		    if ( isset($_POST['action']) 
		         && $_POST['action'] == 'edit_template' 
		         && has_access_to('Pages::Modify Templates'))
		    {
		        if ($pages->write_to_template($_POST))
		        {
		            flash('notice','Template updated');
		        } else {
		            flash('error','Template write failed');
		        }
		    }
		    
		    // show code for given template
		    if ( !empty($_GET['template_name']) )
		    {
		        $this->assign('is_writable',$pages->template_is_writable($_GET['template_name']));
		        $this->assign('template_code',$pages->get_template_code($_GET['template_name']));	        
		        $this->assign('template_name',$_GET['template_name']);
		    }		    
		}
		
		function permissions()
		{
		    if (!has_access_to('Pages::Lock Pages')) {
                flash('error','Sorry but you do not have access');
                $this->redirect_to('index');            
            }
            
            if ( isset($_POST['pages']['id']) )
            {
                $pages = new Pages();
                if ( $pages->page_permissions( (int) $_POST['pages']['id'], $_POST['users']) )
                {
                    $this->render(array('inline'=>'Success: Permissions Updated'));
                } else {
                    $this->render(array('inline'=>'Not updated'));
                }
            }
            
		}
		
		function list_of_pages()
		{
		    $this->use_layout(false);
		    $pages = new Pages();
		    $list = $pages->get_pages_for_js();
		    $this->assign('list',$list);
		}
		
    }

?>